package com.juc.atomics;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author Zan
 * @Create 2024/5/11 14:16
 * @ClassName : AtomicIntegerDemo
 * @Description : TODO 请用一句话描述该类的功能
 */

class MyNumber {
    AtomicInteger atomicInteger = new AtomicInteger();

    public void addPlusPlus() {
        atomicInteger.getAndIncrement();
    }
}

public class AtomicIntegerDemo {

    public static final int SIZE = 50; // 50个线程

    public static void main(String[] args) {

        MyNumber myNumber = new MyNumber();

        CountDownLatch countDownLatch = new CountDownLatch(SIZE);

        for (int i = 1; i <= SIZE; i++) {
            new Thread(() -> {
                try {
                    for (int j = 1; j <= 1000; j++) {
                        myNumber.addPlusPlus();
                    }
                } finally {
                    // 让计数器 - 1，countDown()表示每次计数器的值-1
                    countDownLatch.countDown();
                }
            }, String.valueOf(i)).start();
        }

        // 等待上面50个线程全部计算完成后，再去获得最终值
//        try {
//            TimeUnit.SECONDS.sleep(2);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        try {
            // 等待 (没有为0就一直等待，为0才唤醒，继续往下走)
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + "\t" + "result：" + myNumber.atomicInteger.get());
    }
}
